package com.innjia.sys.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.innjia.base.annotation.SysLog;
import com.innjia.sys.service.impl.QuKuaiUtil;
import com.innjia.base.utils.PageUtils;
import com.innjia.base.utils.Result;
import com.innjia.base.utils.ValidatorUtils;
import com.innjia.sys.entity.ContractInfoEntity;
import com.innjia.sys.entity.HouseEntity;
import com.innjia.sys.entity.UserEntity;
import com.innjia.sys.entity.UserLandlordEntity;
import com.innjia.sys.service.ContractInfoService;
import com.innjia.sys.service.HouseService;
import com.innjia.sys.service.UserLandlordService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 */
@Controller
@RequestMapping("/sys/house")
public class HouseController extends BaseController{

    private static Logger logger = LoggerFactory.getLogger(HouseController.class);

    @Autowired
    private HouseService houseService;

    @Autowired
    private ContractInfoService contractInfoService;

    @Autowired
	private UserLandlordService userLandlordService;
	@Autowired
	private QuKuaiUtil quKuaiUtil;

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("house:save")
    @SysLog("管理员创建房源")
    public Result apply(@RequestBody HouseEntity houseEntity){
        if(houseEntity == null){
        	return Result.error("房源信息格式不正确");
		}
		if(ValidatorUtils.isEmpty(houseEntity.getAddress())
				|| ValidatorUtils.isEmpty(houseEntity.getDistrictName())
				|| ValidatorUtils.isEmpty(houseEntity.getVilage())
				|| ValidatorUtils.isEmpty(houseEntity.getRoomNo())){
			return Result.error("房源地址信息(区县/地址/小区/室)为必填项");
		}
		if(ValidatorUtils.isEmpty(houseEntity.getRentType())){
			return Result.error("请选择租赁方式");
		}
		if(ValidatorUtils.isEquals("合租", houseEntity.getRentType())){
			if(ValidatorUtils.isEmpty(houseEntity.getChildren())
					|| houseEntity.getChildren().size() < 2){
				return Result.error("合租时至少添加2个子房间");
			}
			for(HouseEntity child : houseEntity.getChildren()){
				if(ValidatorUtils.isEmpty(child.getRentalPrice())){
					return Result.error("子房间租金不能为空");
				}
				if(ValidatorUtils.isEmpty(child.getPayMode())){
					return Result.error("子房间付款方式不能为空");
				}
				if(ValidatorUtils.isEmpty(child.getDirect())){
					return Result.error("子房间朝向不能为空");
				}
				if(ValidatorUtils.isEmpty(child.getBuildingArea())){
					return Result.error("子房间房间面积不能为空");
				}
			}
		}else{
			//整租时， 租金付款方式必填
			if(ValidatorUtils.isEmpty(houseEntity.getRentalPrice())){
				return Result.error("请填入租金信息");
			}
			if(ValidatorUtils.isEmpty(houseEntity.getPayMode())){
				return Result.error("请选择付款方式");
			}
		}
		/*if(ValidatorUtils.isEmpty(houseEntity.getBedroomCnt())
				&& ValidatorUtils.isEmpty(houseEntity.getParlourCnt())
				&& ValidatorUtils.isEmpty(houseEntity.getToiletCnt())){
			return Result.error("请填入房间信息");
		}*/

        String userId = this.getUserId();
        houseEntity.setCreatorId(userId);

        try{
			logger.info("house create:" + JSON.toJSON(houseEntity));

			String ownerPhone = houseEntity.getOwnerPhone();
			if(ValidatorUtils.isEmpty(ownerPhone)){
				return Result.error("请输入房东手机");
			}
			/*if(ValidatorUtils.isNotMobile(ownerPhone)){
				return Result.error("手机号码不正确");
			}*/

			UserEntity userEntity = userLandlordService.queryByPhone(ownerPhone);
			if(ValidatorUtils.isEmpty(userEntity)){
				return Result.error("房东不存在");
			}
			houseEntity.setOwnerId(userEntity.getId());

            houseService.create(houseEntity);
            //todo: 区块链

			try {

				String s = quKuaiUtil.saveTransactionWrite(JSONObject.toJSONString(houseEntity));

			} catch (Exception e) {
				e.printStackTrace();
			}

		}catch(org.springframework.dao.DuplicateKeyException e){
            logger.error("房源重复, UNIQUE KEY 冲突", e);

            return Result.error("房源信息重复, 请审核后再试");
        }

		return Result.ok();
    }

	@RequestMapping(method = RequestMethod.PUT)
	@ResponseBody
	@RequiresPermissions("house:update")
	@SysLog("管理员编辑房源")
	public Result edit(@RequestBody HouseEntity houseEntity){
		if(houseEntity == null){
			return Result.error("房源信息格式不正确");
		}
		if(ValidatorUtils.isEmpty(houseEntity.getAddress())
				|| ValidatorUtils.isEmpty(houseEntity.getDistrictName())
				|| ValidatorUtils.isEmpty(houseEntity.getVilage())
				|| ValidatorUtils.isEmpty(houseEntity.getRoomNo())){
			return Result.error("房源地址信息(区县/地址/小区/室)为必填项");
		}
		if(ValidatorUtils.isEmpty(houseEntity.getRentType())){
			return Result.error("请选择租赁方式");
		}
		if(ValidatorUtils.isEquals("合租", houseEntity.getRentType())){
			if(ValidatorUtils.isEmpty(houseEntity.getChildren())
					|| houseEntity.getChildren().size() < 2){
				return Result.error("合租时至少添加2个子房间");
			}
			for(HouseEntity child : houseEntity.getChildren()){
				if(ValidatorUtils.isEmpty(child.getRentalPrice())){
					return Result.error("子房间租金不能为空");
				}
				if(ValidatorUtils.isEmpty(child.getPayMode())){
					return Result.error("子房间付款方式不能为空");
				}
				if(ValidatorUtils.isEmpty(child.getDirect())){
					return Result.error("子房间朝向不能为空");
				}
				if(ValidatorUtils.isEmpty(child.getBuildingArea())){
					return Result.error("子房间房间面积不能为空");
				}
			}
		}else{
			//整租时， 租金付款方式必填
			if(ValidatorUtils.isEmpty(houseEntity.getRentalPrice())){
				return Result.error("请填入租金信息");
			}
			if(ValidatorUtils.isEmpty(houseEntity.getPayMode())){
				return Result.error("请选择付款方式");
			}
		}
		/*if(ValidatorUtils.isEmpty(houseEntity.getBedroomCnt())
				&& ValidatorUtils.isEmpty(houseEntity.getParlourCnt())
				&& ValidatorUtils.isEmpty(houseEntity.getToiletCnt())){
			return Result.error("请填入房间信息");
		}*/

		try{
			logger.info("house edit:" + JSON.toJSON(houseEntity));
			String houseId = houseEntity.getId();
			if(ValidatorUtils.isEmpty(houseId)){
				return Result.error("房源信息错误(ID 不存在)");
			}

			long version = houseEntity.getVersion() == null ? 0l : houseEntity.getVersion();
			HouseEntity oldHouse = houseService.queryDetailById(houseId);
			if(ValidatorUtils.isEmpty(oldHouse)){
				return Result.error("房源不存在");
			}
			if(version != oldHouse.getVersion()){
				return Result.error("房源信息已变更, 请刷新重试");
			}
			if(ValidatorUtils.isEquals("已出租", oldHouse.getRentStatus())){
				return Result.error("已出租状态的房源不可编辑");
			}

			//check 房东信息
			String ownerId = houseEntity.getOwnerId();
			if(ValidatorUtils.isEmpty(ownerId)){
				return Result.error("请选择房东");
			}
			if(ValidatorUtils.isEmpty(userLandlordService.queryObject(ownerId))){
				return Result.error("房东不存在");
			}

			//检查是否有合同
			if(houseService.isHouseWithContract(houseEntity.getId())){
				return Result.error("该房源已签约或者正在签约中, 不可编辑");
			}

			houseService.reset(houseEntity, oldHouse);
		}catch(org.springframework.dao.DuplicateKeyException e){
			logger.error("房源重复, UNIQUE KEY 冲突", e);

			return Result.error("房源信息重复, 请审核后再试");
		}

		return Result.ok();
	}

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Result houseInfo(@PathVariable String id){

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("data", houseService.houseInfo(id));

        return Result.ok(result);
    }

    @RequestMapping(value = "list",method = RequestMethod.GET)
    @ResponseBody
    //@RequiresPermissions("sys:house:query")
    //@SysLog("获取可编辑的房源信息列表")
    public Result list(HttpServletRequest request) {
    	logger.info("===========HouseController.list()start============");
    	Result result = new Result();
    	String  districtName= request.getParameter("districtName");//
    	String rentType = request.getParameter("rentType");//
    	String rentStatus = request.getParameter("rentStatus");//
    	String serialNum = request.getParameter("serialNum");//like
    	String phone = request.getParameter("phone");//like
    	String page = request.getParameter("page");
    	String limit = request.getParameter("limit");

    	HouseEntity houseEntity = new HouseEntity();
    	PageUtils pageUtils = new PageUtils();
    	houseEntity.setDistrictName(StringUtils.isNoneBlank(districtName) ? districtName : null);//
    	houseEntity.setRentType(StringUtils.isNotBlank(rentType) ? rentType : null);//
    	houseEntity.setRentStatus(StringUtils.isNotBlank(rentStatus) ? rentStatus : null);//
    	houseEntity.setSerialNum(StringUtils.isNotBlank(serialNum) ? serialNum : null);//
    	UserLandlordEntity landlord = new UserLandlordEntity();
    	landlord.setPhone(phone);
    	houseEntity.setLandlord(landlord);
    	if(StringUtils.isNotBlank(limit)) {
    		try {
				int pageSize = Integer.parseInt(limit);
				pageUtils.setPageSize(pageSize > 1 ? pageSize : 10);
			} catch (NumberFormatException e) {
				//忽略此错误，使用默认值
				pageUtils.setPageSize(10);
				logger.error("解析limit出错，请确认传递的limit为数字");
			}
    	}
    	if(StringUtils.isNotBlank(page)) {
    		try {
				int currPage = Integer.parseInt(page);
				pageUtils.setCurrPage(currPage > 1 ? currPage : 1);
			} catch (NumberFormatException e) {
				//忽略此错误，使用默认值
				pageUtils.setCurrPage(1);
				logger.error("解析page出错，请确认传递的page为数字");
			}
    	}

    	List<HouseEntity> list = null;
		try {
			list = this.houseService.queryListByBeanPage(houseEntity,pageUtils);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			logger.error("查询列表出现异常，请联系管理员");
			return Result.error("1","查询房源列表失败，请稍后再试");
		}
		//list = this.houseService.transferAllPhones(list);//脱敏
    	pageUtils.setList(list);
    	result.put("page",pageUtils);
    	logger.info("===========HouseController.list()end============");
    	return result;
    }

    @RequestMapping(value = "detail",method = RequestMethod.GET)
    @ResponseBody
    //@RequiresPermissions("sys:house:query")
    //@SysLog("获取房源详情")
    public Result detail(HttpServletRequest request) {
    	logger.info("===========HouseController.detail()start============");
    	Result result = new Result();
    	String  houseId= request.getParameter("houseId");//
    	if(StringUtils.isBlank(houseId)) {
    		logger.info("查询房源详情失败，houseId不能为空");
    		return Result.error("1", "查询房源详情失败，houseId不能为空");
    	}
    	try {
			HouseEntity entity = this.houseService.queryDetailById(houseId);
			//嵌入合同租约信息
			List<ContractInfoEntity> contractInfos = new ArrayList<>();
			if(StringUtils.equals(entity.getRentType(),"整租")) {
				//此房是整租模式
				ContractInfoEntity contractInfo = contractInfoService.queryHouseId(houseId);
				if(contractInfo != null) {
					ContractInfoEntity model = new ContractInfoEntity();
					model.setHouseCode(contractInfo.getHouseCode());
					model.setNetSignCode(contractInfo.getNetSignCode());
					model.setTenantName(contractInfo.getTenantName());
					model.setContractValidityStartTime(contractInfo.getContractValidityStartTime());
					contractInfos.add(model);
				}
			}else {
				//合租模式，获取所有子房间的租约信息
				List<HouseEntity> children = entity.getChildren();
				for (HouseEntity child : children) {
					ContractInfoEntity contractInfo = contractInfoService.queryHouseId(child.getId());
					if(contractInfo != null) {
						ContractInfoEntity model = new ContractInfoEntity();
						model.setHouseCode(contractInfo.getHouseCode());
						model.setNetSignCode(contractInfo.getNetSignCode());
						model.setTenantName(contractInfo.getTenantName());
						model.setContractValidityStartTime(contractInfo.getContractValidityStartTime());
						contractInfos.add(model);
					}
				}
			}
			entity.setContractInfos(contractInfos);
			//房东id为null的时候，赋值""
            UserLandlordEntity landlord = entity.getLandlord();
            if(landlord != null && StringUtils.isBlank(landlord.getIdCard())){
                landlord.setIdCard("");
            }

            //脱敏
//			List<HouseEntity> list = new ArrayList<HouseEntity>();
//			list.add(entity);
//			list = this.houseService.transferAllPhones(list);
			result.put("entity", entity);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			logger.error("查询房源详情出现异常，请联系管理员");
			return Result.error("1","查询房源详情失败，请稍后再试");
		}
    	logger.info("===========HouseController.detail()end============");
    	return result;
    }

    /**
     * 根据houseId查询子房间
     * @param request
     * @return
     */
    @RequestMapping(value = "children",method = RequestMethod.GET)
    @ResponseBody
    //@RequiresPermissions("sys:house:query")
    //@SysLog("获取子房间信息")
    public Result children(HttpServletRequest request) {
    	logger.info("===========HouseController.children()start============");
    	Result result = new Result();
    	String  houseId= request.getParameter("houseId");//
    	if(StringUtils.isBlank(houseId)) {
    		logger.info("查询子房间信息失败，houseId不能为空");
    		return Result.error("1", "查询子房间失败，houseId不能为空");
    	}
    	List<HouseEntity> children = null;
		try {
			children = this.houseService.queryChildrenByParentId(houseId);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			logger.error("查询子房间信息出现异常，请联系管理员");
			return Result.error("1","查询子房间信息失败，请稍后再试");
		}
    	if(children.isEmpty()) {
    		logger.info("查询子房间信息失败，未找到对应的子房间信息");
    		return Result.error("1", "未找到对应的子房间信息");
    	}
    	result.put("children", children);
    	logger.info("===========HouseController.children()end============");
    	return result;
    }


    @RequestMapping(value = "updateRentStatus",method = RequestMethod.GET)
    @ResponseBody
    //@RequiresPermissions("sys:house:query")
    //@SysLog("修改房屋的出租状态")
    public Result updateRentStatus(HttpServletRequest request) {
    	logger.info("===========HouseController.updateRentStatus()start============");
    	try {
			String  houseId= request.getParameter("houseId");//
			String rentStatus = request.getParameter("rentStatus");
			HouseEntity house = this.houseService.getHouseById(houseId);
			if(StringUtils.isBlank(houseId)) {
				logger.info("1","houseId不能为空");
				return Result.error("1", "houseId不能为空");
			}
			if(house == null) {
				logger.info("1","未找到对应的房源，请检查houseId");
				return Result.error("1", "未找到对应的房源，请检查houseId");
			}
			if(StringUtils.isBlank(rentStatus)) {
				logger.info("1","rentStatus不能为空");
				return Result.error("1", "rentStatus不能为空");
			}
			if((!StringUtils.equals(rentStatus, "空置")) && (!StringUtils.equals(rentStatus, "部分出租")) && (!StringUtils.equals(rentStatus, "已出租"))) {
				logger.info("1","请选择正确的租约状态：'空置','部分出租','已出租'");
				return Result.error("1", "请选择正确的租约状态：'空置','部分出租','已出租'");
			}
			this.houseService.updateRentStatus(house,rentStatus);
			logger.info("===========HouseController.updateRentStatus()start============");
			return Result.ok("修改房源出租状态成功");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			logger.error("修改房源出现异常，请联系管理员");
			return Result.error("1","修改房源出租状态失败,请稍后再试");
		}
    }

}
